package cn.wlinker.driver.bacnet.utils;

import cn.hutool.log.StaticLog;
import cn.wlinker.driver.bacnet.domain.BacnetLocalDeviceBean;
import com.serotonin.bacnet4j.LocalDevice;
import com.serotonin.bacnet4j.RemoteDevice;
import com.serotonin.bacnet4j.event.DeviceEventAdapter;
import lombok.SneakyThrows;

/**
 * 自定义监听器，以实时添加新设备到缓存
 *
 * @author gxsjx
 * @version 1.0
 * @date 2022/9/29
 * Copyright © wlinker.cn
 */
public class MyListener extends DeviceEventAdapter {

    private final LocalDevice localDevice;
    private final BacnetLocalDeviceBean bacnetLocalDeviceBean;

    public MyListener(LocalDevice localDevice, BacnetLocalDeviceBean bacnetLocalDeviceBean) {
        this.localDevice = localDevice;
        this.bacnetLocalDeviceBean = bacnetLocalDeviceBean;
    }

    @SneakyThrows
    @Override
    public void iAmReceived(RemoteDevice d) {
        StaticLog.info("LocalDevice[{}] get 'IAm received' message from：{}",localDevice, d);
        LocalDevice localDevice = LocalDeviceCacheUtils.get(bacnetLocalDeviceBean);
        if (localDevice != null) {
            return;
        }
        // 缓存中添加本地设备
        Boolean put = LocalDeviceCacheUtils.put(bacnetLocalDeviceBean, this.localDevice);
        //打印日志
        if (put) {
            StaticLog.info("LocalDevice[{}] add to cache success",this.localDevice);
        } else {
            StaticLog.info("LocalDevice[{}] add to cache fail",this.localDevice);
        }
    }
}